const activityLogService = require('../services/activityLog.service');
const ApiError = require('../utils/apiError');
const { successResponse } = require('../utils/responseFormatter');

/**
 * 获取当前用户的活动日志
 * @param {Object} req Express请求对象
 * @param {Object} res Express响应对象
 * @param {Function} next Express下一个中间件函数
 */
exports.getCurrentUserLogs = async (req, res, next) => {
  try {
    const userId = req.user._id;
    const options = {
      limit: parseInt(req.query.limit) || 20,
      skip: parseInt(req.query.skip) || 0,
      module: req.query.module,
      actionType: req.query.actionType,
      startDate: req.query.startDate,
      endDate: req.query.endDate
    };
    
    const logs = await activityLogService.getUserActivityLogs(userId, options);
    
    return successResponse(res, {
      logs,
      total: logs.length,
      hasMore: logs.length === options.limit
    });
  } catch (error) {
    next(new ApiError(500, '获取活动日志失败', error));
  }
};

/**
 * 获取系统活动日志（仅管理员）
 * @param {Object} req Express请求对象
 * @param {Object} res Express响应对象
 * @param {Function} next Express下一个中间件函数
 */
exports.getSystemLogs = async (req, res, next) => {
  try {
    const options = {
      limit: parseInt(req.query.limit) || 20,
      skip: parseInt(req.query.skip) || 0,
      module: req.query.module,
      actionType: req.query.actionType,
      userType: req.query.userType,
      status: req.query.status,
      startDate: req.query.startDate,
      endDate: req.query.endDate
    };
    
    const logs = await activityLogService.getSystemActivityLogs(options);
    
    // 关联用户信息（如果后续需要）
    // const logsWithUsers = await Promise.all(
    //   logs.map(async (log) => {
    //     // 此处可以添加用户信息关联逻辑
    //     return log;
    //   })
    // );
    
    return successResponse(res, {
      logs,
      total: logs.length,
      hasMore: logs.length === options.limit
    });
  } catch (error) {
    next(new ApiError(500, '获取系统活动日志失败', error));
  }
};

/**
 * 获取特定用户的活动日志（仅管理员）
 * @param {Object} req Express请求对象
 * @param {Object} res Express响应对象
 * @param {Function} next Express下一个中间件函数
 */
exports.getUserLogs = async (req, res, next) => {
  try {
    const userId = req.params.userId;
    
    const options = {
      limit: parseInt(req.query.limit) || 20,
      skip: parseInt(req.query.skip) || 0,
      module: req.query.module,
      actionType: req.query.actionType,
      startDate: req.query.startDate,
      endDate: req.query.endDate
    };
    
    const logs = await activityLogService.getUserActivityLogs(userId, options);
    
    return successResponse(res, {
      logs,
      userId,
      total: logs.length,
      hasMore: logs.length === options.limit
    });
  } catch (error) {
    next(new ApiError(500, '获取用户活动日志失败', error));
  }
};

/**
 * 获取特定模块的活动日志
 * @param {Object} req Express请求对象
 * @param {Object} res Express响应对象
 * @param {Function} next Express下一个中间件函数
 */
exports.getModuleLogs = async (req, res, next) => {
  try {
    const moduleName = req.params.module;
    
    const options = {
      limit: parseInt(req.query.limit) || 20,
      skip: parseInt(req.query.skip) || 0,
      module: moduleName,
      actionType: req.query.actionType,
      userType: req.query.userType,
      status: req.query.status,
      startDate: req.query.startDate,
      endDate: req.query.endDate
    };
    
    const logs = await activityLogService.getSystemActivityLogs(options);
    
    return successResponse(res, {
      logs,
      module: moduleName,
      total: logs.length,
      hasMore: logs.length === options.limit
    });
  } catch (error) {
    next(new ApiError(500, '获取模块活动日志失败', error));
  }
};

/**
 * 获取活动日志统计信息（仅管理员）
 * @param {Object} req Express请求对象
 * @param {Object} res Express响应对象
 * @param {Function} next Express下一个中间件函数
 */
exports.getActivityStats = async (req, res, next) => {
  try {
    // 这里可以实现更复杂的统计逻辑
    // 示例只是一个基本实现
    const UserActivityLog = require('../models/userActivityLog.model');
    
    const startDate = req.query.startDate ? new Date(req.query.startDate) : new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); // 默认7天
    const endDate = req.query.endDate ? new Date(req.query.endDate) : new Date();
    
    // 获取模块统计
    const moduleStats = await UserActivityLog.aggregate([
      { 
        $match: { 
          createdAt: { $gte: startDate, $lte: endDate } 
        } 
      },
      { 
        $group: { 
          _id: '$module', 
          count: { $sum: 1 } 
        } 
      },
      { 
        $sort: { 
          count: -1 
        } 
      }
    ]);
    
    // 获取操作类型统计
    const actionStats = await UserActivityLog.aggregate([
      { 
        $match: { 
          createdAt: { $gte: startDate, $lte: endDate } 
        } 
      },
      { 
        $group: { 
          _id: '$actionType', 
          count: { $sum: 1 } 
        } 
      },
      { 
        $sort: { 
          count: -1 
        } 
      }
    ]);
    
    // 获取每日活动统计
    const dailyStats = await UserActivityLog.aggregate([
      { 
        $match: { 
          createdAt: { $gte: startDate, $lte: endDate } 
        } 
      },
      { 
        $group: { 
          _id: { 
            $dateToString: { 
              format: '%Y-%m-%d', 
              date: '$createdAt' 
            } 
          }, 
          count: { $sum: 1 } 
        } 
      },
      { 
        $sort: { 
          _id: 1 
        } 
      }
    ]);
    
    // 获取用户类型统计
    const userTypeStats = await UserActivityLog.aggregate([
      { 
        $match: { 
          createdAt: { $gte: startDate, $lte: endDate } 
        } 
      },
      { 
        $group: { 
          _id: '$userType', 
          count: { $sum: 1 } 
        } 
      }
    ]);
    
    return successResponse(res, {
      periodStart: startDate,
      periodEnd: endDate,
      totalActivities: await UserActivityLog.countDocuments({
        createdAt: { $gte: startDate, $lte: endDate }
      }),
      moduleStats,
      actionStats,
      dailyStats,
      userTypeStats
    });
  } catch (error) {
    next(new ApiError(500, '获取活动统计失败', error));
  }
}; 